{{ template "layout/header" .}}
{{/*<script src="//cdn.ckeditor.com/4.12.1/full/ckeditor.js"></script>*/}}
{{/*<script src="/static/ckeditor/ckeditor.js"></script>*/}}
<link rel="stylesheet" href="/static/css/ckstyles.css">
<script src="/static/js/ck5b/ckeditor.js"></script>
<main id="body">
    <div class="container">
        <div class="row">
            <div class="col-lg-10 mx-auto">
                <div class="card">
                    <div class="card-header">
                        更新主题
                    </div>
                    <div class="card-body">
                        <form action="/api/v1/thread/{{.thread.ID}}/update" method="post" id="threadform">
                            <input type="hidden" name="doctype" value="0">
                            <input type="hidden" name="post_id" value="{{.fpost.ID}}">
                            {{/*<input type="hidden" name="thread_id" value="{{.thread.ID}}">*/}}
                            <div class="form-group">
                                <select id="select_forum_id" class="custom-select mr-1 w-auto" name="forum_id">
                                    {{$checkedFid := .thread.ForumID}}
                                    {{range .forums}}
                                    <option value="{{.ID}}" {{if eq .ID $checkedFid}} selected="selected" {{end}}>{{.Name}}</option>
                                    {{end}}
                                </select>
                            </div>
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="标题" name="subject" value="{{.thread.Subject}}" id="subject">
                            </div>
                            <div id="nav_tag_list_div">
                                <table class="small nav_tag_list mb-2"></table>
                            </div>
                            <div class="form-group">
                                <div class="edui-container" style="width: 100%; z-index: 999;">
                                    <div class="edui-editor-body message">
                                        <textarea class="form-control" placeholder="内容" name="message" id="message" style="height: 300px; display: none;">
                                            {{.fpost.Message}}
                                        </textarea>
                                    </div>
                                </div>
                            </div>
                            {{ template "layout/captcha" .}}
                            <div class="d-flex justify-content-between">
                                <div class="attachlist_parent">
                                    <a class="small text-left" href="javascript:void(0)">
                                        <label class="addattach" id="addattach">
                                            <i class="icon-folder-open-o"></i>
                                            添加附件
                                            <input type="file" id="add_attach" multiple="multiple" class="invisible">
                                        </label>
                                    </a>
                                    {{if .attachs}}
                                    <fieldset class="fieldset">
                                        <legend>上传的附件：</legend>
                                        <ul class="attachlist">
                                            {{range .attachs}}
                                            <li aid="{{.ID}}">
                                                <a href="/{{.Filename}}" target="_blank">
                                                    <i class="icon filetype {{.Filetype}}"></i>
                                                    {{.Orgfilename}}
                                                </a>
                                                <a onclick="deleteAttach(this, {{.ThreadID}}, {{.ID}})" href="javascript:void(0)" class="delete ml-3"><i class="icon-remove"></i> 删除</a>
                                            </li>
                                            {{end}}
                                        </ul>
                                    </fieldset>
                                    {{end}}

                                </div>
                                <div class="text-right">
                                    <button type="button" class="btn btn-primary" id="threadsubmit" data-loading-text="正在提交..."> 更新主题
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>
<script>
//判断是否已登录  如未登录 跳转到登录页
if (!{{.islogin}}) {
    location.href="/login.html"
}
if ({{.thread.UserID}} != {{.sessions.Userid}}) {
    $.alert("您没有权限编辑")
    setTimeout(function () {
        location.href = "/"
    },2000)
}

var myeditor = null;
ClassicEditor.create(document.querySelector('#message'), {

    toolbar: {
        items: [
            'exportPdf',
            'heading',
            '|',
            'bold',
            'italic',
            'underline',
            'fontColor',
            'fontSize',
            'fontFamily',
            'highlight',
            'alignment',
            'link',
            'bulletedList',
            'numberedList',
            '|',
            'indent',
            'outdent',
            '|',
            'imageUpload',
            'blockQuote',
            'insertTable',
            'mediaEmbed',
            'undo',
            'redo',
            '|',
            'codeBlock',
            'code',
            'horizontalLine'
        ]
    },
    language: 'zh-cn',
    image: {
        toolbar: [
            'imageTextAlternative',
            'imageStyle:full',
            'imageStyle:side'
        ]
    },
    table: {
        contentToolbar: [
            'tableColumn',
            'tableRow',
            'mergeTableCells'
        ]
    },
    licenseKey: '',
    ckfinder:{
        'uploadUrl':'/api/v1/image/upload',
    },

})
    .then(editor => {
        myeditor = editor
    })
    .catch(error => {
        console.error('Oops, something went wrong!');
        console.error(error);
    });

var qrform = $("#threadform")
var jsubmit = $('#threadsubmit');
var attachUploader = $("#add_attach");
var jattachparent = $('.attachlist_parent');
var maxSize = 1*1024*1024

jsubmit.on('click', function() {
    qrform.reset();

    var postdata = qrform.serializeObject();
    if (postdata.subject.length <= 5) {
        $.alert("标题不能为空切不能小于5个字")
        return
    }

    postdata.message = myeditor.getData();
    console.log(postdata)
    if (postdata.message.length < 30) {
        $.alert("内容不能为空切不能小于30字")
        return
    }

    // 验证验证码
    var captcha = getCaptcha()
    var captchaKey = getCaptchaKey()
    captchaPass = virefyCaptcha(captcha, captchaKey)
    if (captcha.length == 0) {
        $.alert("验证码不能为空")
        return
    } else {
        if (captchaPass != 200 ) {
            $.alert("验证码错误")
            refreshCaptcha()
            jsubmit.button('reset');
            return
        }
    }

    var content = postdata.message + postdata.subject
    var sensitive = false
    $.ajax({
        type: 'POST',
        url: "/api/v1/content_check",
        async:false,
        data: {"content":content},
        success: function(r){
            console.log(r)
            if (r.code != 201) {
                $.alert(r.message)
                refreshCaptcha()
                sensitive = true
                return
            }
        }
    })

    if (sensitive) {
        return
    }

    jsubmit.button('loading');

    $.xpost(qrform.attr('action'), postdata, function(code, message) {
        console.log(code, ":", message)
        if (code == 200) {
            afterAddNewThread()
            $.alert(message);
            setTimeout(function(){
                href = "/forum/"+ $("#select_forum_id").val() +"/list.html"
                location.href = href
            }, 2000)
        } else if (code < 0) {
            $.alert(message);
            jsubmit.button('reset');
        } else {
            jform.find('[name="' + code + '"]').alert(message).focus();
            jsubmit.button('reset');
        }
    });

    return false;
});

function afterAddNewThread() {
    var jsubmit = $('#postsubmit')
    jsubmit.button('reset');
}

function trimChar(str, char, type) {
    if (char) {
        if (type == 'left') {
            return str.replace(new RegExp('^\\'+char+'+', 'g'), '');
        } else if (type == 'right') {
            return str.replace(new RegExp('\\'+char+'+$', 'g'), '');
        }
        return str.replace(new RegExp('^\\'+char+'+|\\'+char+'+$', 'g'), '');
    }
    return str.replace(/^\s+|\s+$/g, '');
}

attachUploader.on('change', function (e) {
    sessionStorage.setItem("test", 1)
    var fd = new FormData()
    attachfile = attachUploader[0].files[0]
    console.log(attachfile)

    var filesSize = attachfile.size
    // 禁止上传大于1m的文件
    console.log(attachfile.size)
    if (filesSize > maxSize) {
        $.alert("文件大于1M，不能上传")
        return
    }

    fd.append("upload", attachfile)
    fd.append("thread_id", {{.thread.ID}})
    fd.append("post_id", {{.fpost.ID}})
    $.ajax({
        url: "/api/v1/attach/add",
        data: fd,
        type: "POST",
        contentType: false,
        processData:false,
        success: function(res) {
            //成功
            console.log(res)
            // return
            if (res.code == 200) {
                // 并发下会 服务端 session 写入会有问题，由客户端控制改为串行
                if (!jattachparent.find('.attachlist').length) {
                    jattachparent.append('<fieldset class="fieldset"><legend>上传的附件</legend><ul class="attachlist"><ul></fieldset>');
                }
                // 添加福建区域
                message = res.data
                addAttachLi(message.url, message.filetype, 1, message.orgfilename)

                $.alert("上传成功")
                /*setTimeout(function(){
                    location.reload()
                }, 2000)*/
            } else {
                $.alert(res.message)
                return
            }
        }
    })
});

function addAttachLi(url, filetype, aid, orgfilename) {
    $('.attachlist').append('<li aid="' + aid + '"><a class="attachfile" orgfilename="' + orgfilename + '"  href="' + message.url + '" target="_blank"><i class="icon filetype ' + filetype + '"></i> ' + orgfilename + '</a> <a onclick="deleteAttach(this, {{.thread.ID}}, '+ aid +')"  href="javascript:void(0);" class="delete ml-2"><i class="icon-remove"></i> 删除</a></li>');
}

function deleteAttach(elem, threadId, attachId) {
    var fd = new FormData()
    fd.append("thread_id", threadId)
    fd.append("attach_id", attachId)
    $.ajax({
        url: "/api/v1/attach/delete",
        data: fd,
        type: "POST",
        contentType: false,
        processData:false,
        success: function(res) {
            //成功
            console.log(res)
            // return
            if (res.code == 200) {
                if ($('.attachlist').find("li").length == 1) {
                    $('.fieldset').remove()
                } else {
                    $(elem).parent().remove()
                }
            } else {
                $.alert(res.message)
                return
            }
        }
    })
}
</script>
{{ template "layout/footer" .}}